﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ArbabTravelsERP.DAL;
using ArbabTravelsERP.Models;
using System.IO;
using System.Configuration;

namespace ArbabTravelsERP.Controllers
{
    public class DoctorController : Controller
    {
        DAL.Master dal = new Master();
        CandidateDAL candDAL = new CandidateDAL();
        //
        // GET: /Doctor/
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Create()
        {
            CandidateModel cand = new CandidateModel();
            DataSet ds = new DataSet();
            GetAllMaster();
            ViewData["RegNo"] = "DC" + DateTime.Now.ToString("yyyyMMddhhmmss"); ;

            Session["SaveAddressDetails"] = ds;
            cand.GetAddressDetails = ds;
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(CandidateModel cand)
        {
            //if (ModelState.IsValid)
            //{
            var filePath = string.Empty;

            if (!string.IsNullOrEmpty(cand.USER_IMAGE_PATH))
            {
                var path = string.Empty;
                filePath = Convert.ToString("..\\DoctorImage\\" + DateTime.Now.ToString("yyyyMMddhhmmss")) + "_" + Path.GetFileName(cand.USER_IMAGE_PATH.ToString());
                var fileName = Convert.ToString(DateTime.Now.ToString("yyyyMMddhhmmss")) + "_" + Path.GetFileName(cand.USER_IMAGE_PATH.ToString());
                FileInfo file = new FileInfo(Server.MapPath("~/DoctorImage/" + Convert.ToString(cand.REGISTRATION_NO) + "_" + Convert.ToString(fileName)));

                if (file.Exists)
                {
                    file.Delete();
                }

                FileInfo file1 = new FileInfo(cand.USER_IMAGE_PATH);
                path = Path.Combine(Server.MapPath("~/DoctorImage/") + "_" + Convert.ToString(fileName));
                file1.CopyTo(path);

            }

            DataTable dt = null;
            dt = candDAL.InsertCandidateDetails(cand, filePath);
            candDAL.InsertCandidatePersonalDetails(cand);

            DataSet dtaddress = (DataSet)Session["SaveAddressDetails"];
            if (dtaddress != null)
            {
                #region Save Address

                //===================Saving ADDRESS Details=================================//
                if (dtaddress.Tables["AddressDetails"] != null)
                {
                    if (dtaddress.Tables["AddressDetails"].Rows.Count > 0)
                    {
                        for (int i = 0; i < dtaddress.Tables["AddressDetails"].Rows.Count; i++)
                        {
                            cand.ADDRESS_TYPE_ID = Convert.ToInt32(dtaddress.Tables["AddressDetails"].Rows[i]["ADDRESS_TYPE_ID"].ToString());
                            cand.ADDRESS = Convert.ToString(dtaddress.Tables["AddressDetails"].Rows[i]["Address"].ToString());
                            cand.CITY_CODE = Convert.ToString(dtaddress.Tables["AddressDetails"].Rows[i]["CITY_CODE"].ToString());
                            cand.PIN_CODE = Convert.ToString(dtaddress.Tables["AddressDetails"].Rows[i]["Pin_Code"].ToString());
                            cand.VILLAGE = Convert.ToString(dtaddress.Tables["AddressDetails"].Rows[i]["Village"].ToString());

                            candDAL.SaveAddressDetails(cand, "SAVE_ADDRESS");
                        }
                    }
                }
                //===================Saving ADDRESS Details=================================//

                #endregion

                #region Save Phone

                //===================Saving Phone Details=================================//
                if (dtaddress.Tables["PhoneDetails"] != null)
                {
                    if (dtaddress.Tables["PhoneDetails"].Rows.Count > 0)
                    {
                        for (int i = 0; i < dtaddress.Tables["PhoneDetails"].Rows.Count; i++)
                        {
                            cand.PHONE_TYPE_ID = Convert.ToString(dtaddress.Tables["PhoneDetails"].Rows[i]["PHONE_TYPE_ID"].ToString());
                            cand.PHONE_NO = Convert.ToString(dtaddress.Tables["PhoneDetails"].Rows[i]["PHONE_NO"].ToString());

                            candDAL.SaveContactDetails(cand, "SAVE_PHONE");
                        }
                    }
                }
                //===================Saving Phone Details=================================//
                #endregion

                #region Save Email

                //===================Saving Email Details=================================//
                if (dtaddress.Tables["EmailDetails"] != null)
                {
                    if (dtaddress.Tables["EmailDetails"].Rows.Count > 0)
                    {
                        for (int i = 0; i < dtaddress.Tables["EmailDetails"].Rows.Count; i++)
                        {
                            cand.EMAIL_ID = Convert.ToString(dtaddress.Tables["EmailDetails"].Rows[i]["EMAIL_ID"].ToString());

                            candDAL.SaveEmailDetails(cand, "SAVE_EMAIL");
                        }
                    }
                }
                //===================Saving Email Details=================================//
                #endregion

            }

            if (dt.Rows[0]["Error"].ToString() == "Successfull")
            {
                DataSet ds = new DataSet();
                TempData["Success"] = "Success! Well done its submitted.";

                return RedirectToAction("Create");
            }

            //}
            ViewData["RegNo"] = cand.REGISTRATION_NO;
            GetAllMaster();
            return View(cand);
        }

        private void GetAllMaster()
        {
            All_Master master = new All_Master();
            ViewData["GetCountryStateCity"] = master.GetCountryStateCity();
            ViewData["GetAddressType"] = master.GetAddressType();
        }

        #region Master

        public JsonResult GetCityByStateCode(string State_code)
        {
            if (System.Web.HttpContext.Current.Cache["dtCountryStateCity"] == null)
            {
                System.Web.HttpContext.Current.Cache["dtCountryStateCity"] = dal.GetCountryStateCity();
            }

            DataTable dtcity = new DataTable();
            if (((DataTable)System.Web.HttpContext.Current.Cache["dtCountryStateCity"]).Select("State_Code='" + State_code + "'").Length > 0)
                dtcity = ((DataTable)System.Web.HttpContext.Current.Cache["dtCountryStateCity"]).Select("State_Code='" + State_code + "'").CopyToDataTable();

            var city = (from city_code in dtcity.AsEnumerable()
                        select new SelectListItem
                        {
                            Value = city_code.Field<string>("City_code"),
                            Text = city_code.Field<string>("City_name")
                        }).ToList();

            return Json(new SelectList(city, "Value", "Text"));
        }

        public JsonResult GetStateByCountryCode(string Country_code)
        {
            if (System.Web.HttpContext.Current.Cache["dtCountryStateCity"] == null)
            {
                System.Web.HttpContext.Current.Cache["dtCountryStateCity"] = dal.GetCountryStateCity();
            }

            DataTable dtcity = new DataTable();
            if (((DataTable)System.Web.HttpContext.Current.Cache["dtCountryStateCity"]).Select("Country_Code='" + Country_code + "'").Length > 0)
                dtcity = ((DataTable)System.Web.HttpContext.Current.Cache["dtCountryStateCity"]).Select("Country_Code='" + Country_code + "'").CopyToDataTable();

            var city = (from city_code in dtcity.AsEnumerable()
                        select new SelectListItem
                        {
                            Value = city_code.Field<string>("State_code"),
                            Text = city_code.Field<string>("State_name")
                        }).ToList();

            return Json(new SelectList(city, "Value", "Text"));
        }

        #endregion

        #region Address

        public JsonResult SaveAddressDetails(int address_type, string address, string citycode, string pincode, string village, string regno)
        {
            JsonResult json = new JsonResult();
            DataSet ds = new DataSet();

            if (System.Web.HttpContext.Current.Cache["dtCountryStateCity"] == null)
            {
                System.Web.HttpContext.Current.Cache["dtCountryStateCity"] = dal.GetCountryStateCity();
            }
            DataTable dtcity = ((DataTable)System.Web.HttpContext.Current.Cache["dtCountryStateCity"]).Select("CITY_CODE='" + citycode + "'").CopyToDataTable();
            string country_name = dtcity.Rows[0]["COUNTRY_NAME"].ToString();
            string statecity = dtcity.Rows[0]["STATE_NAME"].ToString() + "-" + dtcity.Rows[0]["CITY_NAME"].ToString();

            DataTable dtAddressType = ((DataTable)System.Web.HttpContext.Current.Cache["AddressType"]).Select("ADDRESS_TYPE_ID='" + address_type + "'").CopyToDataTable();
            string addresstype = dtAddressType.Rows[0]["ADDRESS_TYPE"].ToString();

            DataSet dtaddress = (DataSet)Session["SaveAddressDetails"];

            if (dtaddress.Tables["AddressDetails"] != null)
            {
                if (dtaddress.Tables["AddressDetails"].Rows.Count > 0)
                {
                    DataRow newRow = dtaddress.Tables["AddressDetails"].NewRow();
                    // newRow["ID"] = dtaddress.Tables["AddressDetails"].Rows.Count + 1;
                    newRow["ADDRESS_TYPE_ID"] = address_type;
                    newRow["Address"] = addresstype + "-" + address;
                    newRow["CITY_CODE"] = citycode;
                    newRow["Pin_Code"] = pincode;
                    newRow["Village"] = village;
                    newRow["Country"] = country_name;
                    newRow["StateCity"] = statecity;
                    dtaddress.Tables["AddressDetails"].Rows.Add(newRow);

                }
                else
                {
                    DataRow newRow = dtaddress.Tables["AddressDetails"].NewRow();
                    // newRow["ID"] =  1;
                    newRow["ADDRESS_TYPE_ID"] = address_type;
                    newRow["Address"] = addresstype + "-" + address;
                    newRow["CITY_CODE"] = citycode;
                    newRow["Pin_Code"] = pincode;
                    newRow["Village"] = village;
                    newRow["Country"] = country_name;
                    newRow["StateCity"] = statecity;
                    dtaddress.Tables["AddressDetails"].Rows.Add(newRow);
                }

            }
            else
            {
                DataTable dt = new DataTable();
                dt.TableName = "AddressDetails";


                DataColumn DC = new DataColumn();
                DataColumn id = new DataColumn("ID", typeof(Int32));
                //  DC = dt.Columns.Add("ID");
                id.AutoIncrement = true;
                id.AutoIncrementSeed = 1;
                id.AutoIncrementStep = 1;
                dt.Columns.Add(id);
                DC = dt.Columns.Add("ADDRESS_TYPE_ID");
                DC = dt.Columns.Add("Address");
                DC = dt.Columns.Add("CITY_CODE");
                DC = dt.Columns.Add("Pin_Code");
                DC = dt.Columns.Add("Village");
                DC = dt.Columns.Add("Country");
                DC = dt.Columns.Add("StateCity");


                DataRow newRow = dt.NewRow();
                // newRow["ID"] =  1;
                newRow["ADDRESS_TYPE_ID"] = address_type;
                newRow["Address"] = addresstype + "-" + address;
                newRow["CITY_CODE"] = citycode;
                newRow["Pin_Code"] = pincode;
                newRow["Village"] = village;
                newRow["Country"] = country_name;
                newRow["StateCity"] = statecity;

                dt.Rows.Add(newRow);

                dtaddress.Tables.Add(dt);

            }

            Session["SaveAddressDetails"] = dtaddress;

            string returnData = GetJson(dtaddress.Tables["AddressDetails"]);
            json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            json.Data = returnData;
            return json;
        }

        public JsonResult DeleteAddressDetails(int addressid)
        {
            JsonResult json = new JsonResult();
            DataSet dtaddress = (DataSet)Session["SaveAddressDetails"];

            var query = dtaddress.Tables["AddressDetails"].AsEnumerable().Where(r => r.Field<Int32>("ID") == addressid);

            foreach (var row in query.ToList())
                row.Delete();

            Session["SaveAddressDetails"] = dtaddress;

            string returnData = GetJson(dtaddress.Tables["AddressDetails"]);
            json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            json.Data = returnData;
            return json;
        }

        #endregion

        #region Email

        public JsonResult SaveEmailDetails(string EmailId)
        {
            JsonResult json = new JsonResult();
            DataSet ds = new DataSet();
            DataSet dtaddress = (DataSet)Session["SaveAddressDetails"];

            if (dtaddress.Tables["EmailDetails"] != null)
            {
                if (dtaddress.Tables["EmailDetails"].Rows.Count > 0)
                {
                    DataRow newRow = dtaddress.Tables["EmailDetails"].NewRow();
                    // newRow["ID"] = dtaddress.Tables["AddressDetails"].Rows.Count + 1;
                    newRow["EMAIL_ID"] = EmailId;
                    dtaddress.Tables["EmailDetails"].Rows.Add(newRow);

                }
                else
                {
                    DataRow newRow = dtaddress.Tables["EmailDetails"].NewRow();
                    // newRow["ID"] =  1;
                    newRow["EMAIL_ID"] = EmailId;
                    dtaddress.Tables["EmailDetails"].Rows.Add(newRow);
                }

            }
            else
            {
                DataTable dt = new DataTable();
                dt.TableName = "EmailDetails";

                DataColumn DC = new DataColumn();
                DataColumn id = new DataColumn("ID", typeof(Int32));
                //  DC = dt.Columns.Add("ID");
                id.AutoIncrement = true;
                id.AutoIncrementSeed = 1;
                id.AutoIncrementStep = 1;
                dt.Columns.Add(id);
                DC = dt.Columns.Add("EMAIL_ID");

                DataRow newRow = dt.NewRow();
                // newRow["ID"] =  1;
                newRow["EMAIL_ID"] = EmailId;

                dt.Rows.Add(newRow);

                dtaddress.Tables.Add(dt);

            }

            Session["SaveAddressDetails"] = dtaddress;

            string returnData = GetJson(dtaddress.Tables["EmailDetails"]);
            json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            json.Data = returnData;
            return json;
        }

        public JsonResult DeleteEmailDetails(int emailid)
        {
            JsonResult json = new JsonResult();
            DataSet dtaddress = (DataSet)Session["SaveAddressDetails"];

            var query = dtaddress.Tables["EmailDetails"].AsEnumerable().Where(r => r.Field<Int32>("ID") == emailid);

            foreach (var row in query.ToList())
                row.Delete();

            Session["SaveAddressDetails"] = dtaddress;

            string returnData = GetJson(dtaddress.Tables["EmailDetails"]);
            json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            json.Data = returnData;
            return json;
        }

        #endregion

        #region phone
        public JsonResult SavePhoneDetails(string PHONE_TYPE_ID, string PHONE_NO)
        {
            JsonResult json = new JsonResult();
            DataSet ds = new DataSet();
            DataSet dtaddress = (DataSet)Session["SaveAddressDetails"];

            if (dtaddress.Tables["PhoneDetails"] != null)
            {
                if (dtaddress.Tables["PhoneDetails"].Rows.Count > 0)
                {
                    DataRow newRow = dtaddress.Tables["PhoneDetails"].NewRow();
                    // newRow["ID"] = dtaddress.Tables["AddressDetails"].Rows.Count + 1;

                    newRow["PHONE_TYPE_ID"] = PHONE_TYPE_ID;
                    newRow["PHONE_NO"] = PHONE_NO;
                    dtaddress.Tables["PhoneDetails"].Rows.Add(newRow);

                }
                else
                {
                    DataRow newRow = dtaddress.Tables["PhoneDetails"].NewRow();
                    // newRow["ID"] =  1;
                    newRow["PHONE_TYPE_ID"] = PHONE_TYPE_ID;
                    newRow["PHONE_NO"] = PHONE_NO;
                    dtaddress.Tables["PhoneDetails"].Rows.Add(newRow);
                }

            }
            else
            {
                DataTable dt = new DataTable();
                dt.TableName = "PhoneDetails";

                DataColumn DC = new DataColumn();
                DataColumn id = new DataColumn("ID", typeof(Int32));
                //  DC = dt.Columns.Add("ID");
                id.AutoIncrement = true;
                id.AutoIncrementSeed = 1;
                id.AutoIncrementStep = 1;
                dt.Columns.Add(id);
                DC = dt.Columns.Add("PHONE_TYPE_ID");
                DC = dt.Columns.Add("PHONE_NO");

                DataRow newRow = dt.NewRow();
                // newRow["ID"] =  1;
                newRow["PHONE_TYPE_ID"] = PHONE_TYPE_ID;
                newRow["PHONE_NO"] = PHONE_NO;

                dt.Rows.Add(newRow);

                dtaddress.Tables.Add(dt);

            }

            Session["SaveAddressDetails"] = dtaddress;

            string returnData = GetJson(dtaddress.Tables["PhoneDetails"]);
            json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            json.Data = returnData;
            return json;
        }

        public JsonResult DeletePhoneDetails(int phoneid)
        {
            JsonResult json = new JsonResult();
            DataSet dtaddress = (DataSet)Session["SaveAddressDetails"];

            var query = dtaddress.Tables["PhoneDetails"].AsEnumerable().Where(r => r.Field<Int32>("ID") == phoneid);

            foreach (var row in query.ToList())
                row.Delete();

            Session["SaveAddressDetails"] = dtaddress;

            string returnData = GetJson(dtaddress.Tables["PhoneDetails"]);
            json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            json.Data = returnData;
            return json;
        }

        #endregion

        public static string GetJson(DataTable dt)
        {
            System.Web.Script.Serialization.JavaScriptSerializer serializer =
               new System.Web.Script.Serialization.JavaScriptSerializer();
            List<Dictionary<string, object>> rows =
               new List<Dictionary<string, object>>();
            Dictionary<string, object> row = null;

            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }
            return serializer.Serialize(rows);
        }

    }
}